package com.test.multithread.lock.interrupt;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class InterruptibleLockExample {
    private final Lock lock = new ReentrantLock();

    public void performTask() throws InterruptedException {
        lock.lockInterruptibly();
        try {
            // 模拟长时间任务
            System.out.println(Thread.currentThread().getName() + " 获得了锁，开始执行任务");
            TimeUnit.SECONDS.sleep(5);
        } finally {
            lock.unlock();
            System.out.println(Thread.currentThread().getName() + " 释放了锁");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        InterruptibleLockExample example = new InterruptibleLockExample();
        ExecutorService executor = Executors.newSingleThreadExecutor();

        executor.submit(() -> {
            try {
                example.performTask();
            } catch (InterruptedException e) {
                System.out.println("任务被中断");
            }
        });

        // 主线程等待一段时间后取消任务
        TimeUnit.SECONDS.sleep(4);
        executor.shutdownNow(); // 尝试立即取消所有正在执行的任务

        System.out.println("尝试取消任务");
        executor.awaitTermination(1, TimeUnit.SECONDS); // 等待任务终止
    }
}